package com.cchip.cloud;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.cchip.cloud.api.MeetingApi;
import com.cchip.cloud.api.MeetingReturned;
import com.cchip.cloud.db.MeetingDb;
import com.cchip.cloud.system.BackgroundRunner;
import com.cchip.cloud.system.Favorite;
import com.cchip.cloud.system.Meeting;

public class RoomActivity extends Activity implements OnItemClickListener {

	private EditText mRoomIdEtxt = null;
	private Button mEnterBtn = null;
	private GridView mFavGrid = null;

	private SimpleAdapter mAdapter = null;
	private List<Favorite> mFavs = null;
	private String mRoomId = null;

	private MeetingApi mMeetingApi = MeetingApi.getInstance();
	private Requester mRequester = null;
	private Refresher mRefresher = null;
	private static final int REQ_KNOCK_ROOM = 13;
	private static final int REQ_ENTER_ROOM = 14;
	private static final int REFRESH_SHOW_PASSWORD_DIALOG = 23;
	private static final int REFRESH_ENTER_MEETING_ROOM = 24;

	private Activity context = null;
	private ProgressDialog mWaitDialog = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = this;
		setContentView(R.layout.room);

		mRequester = new Requester(BackgroundRunner.getRunner());
		mRefresher = new Refresher();

		mRoomIdEtxt = (EditText) findViewById(R.id.room_id);
		mEnterBtn = (Button) findViewById(R.id.enter_room);
		mFavGrid = (GridView) findViewById(R.id.fav_room_grid);

		mEnterBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				showWaitDialog();
				mRoomId = mRoomIdEtxt.getText().toString().trim();
				mRequester.sendEmptyMessage(REQ_KNOCK_ROOM);
			}

		});

		mFavGrid.setOnItemClickListener(this);
	}

	@Override
	public void onStart() {
		super.onStart();

		mFavs = MeetingDb.getInstance(this).getFavorite(8);

		String[] from = { Favorite.KEY_ROOM_NAME, Favorite.KEY_ROOM_ID };
		int[] to = { R.id.room_name, R.id.room_id };
		mAdapter = new SimpleAdapter(this, mFavs, R.layout.fav_room_item, from,
				to);
		mFavGrid.setAdapter(mAdapter);
	}

	private void showWaitDialog() {
		mWaitDialog = new ProgressDialog(this, ProgressDialog.STYLE_SPINNER);
		mWaitDialog.setMessage("正在进入会议室，等稍候...");
		mWaitDialog.setCancelable(false);
		mWaitDialog.show();
	}

	private void showPasswordDialog() {
		LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View root = inflater.inflate(R.layout.password, null);
		final EditText passwordEtxt = (EditText) root
				.findViewById(R.id.room_password);

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("此会议室已加密");
		builder.setView(root);
		builder.setNeutralButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				showWaitDialog();
				Message msg = new Message();
				msg.what = REQ_ENTER_ROOM;
				msg.obj = passwordEtxt.getText().toString();
				mRequester.sendMessage(msg);
			}

		});
		builder.show();

	}

	private class Requester extends Handler {

		public Requester(Looper looper) {
			super(looper);
		}

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			String roomPassowrd = "";

			switch (msg.what) {
			case REQ_KNOCK_ROOM:
				MeetingReturned ret = mMeetingApi.knockRoom(mRoomId);

				if (ret != null) {

					if (ret.operCode == MeetingReturned.CODE_OK) {
						if (ret.needPassword) {
							mRefresher
									.sendEmptyMessage(REFRESH_SHOW_PASSWORD_DIALOG);
						} else {
							MeetingReturned ret2 = mMeetingApi.enterRoom(
									mRoomId, roomPassowrd);
							if (ret2 != null) {
								if (ret2.operCode == MeetingReturned.CODE_OK) {
									Meeting.current.roomId = mRoomId;
									Meeting.current.roomName = ret2.roomName;
									Meeting.current.baseTime = SystemClock
											.elapsedRealtime();
									Meeting.current.startTime = System
											.currentTimeMillis();
									Meeting.current.isMute = false;
									mRefresher
											.sendEmptyMessage(REFRESH_ENTER_MEETING_ROOM);
								} else {
									mRefresher.sendEmptyMessage(ret2.operCode);
								}
							} else {
								mRefresher
										.sendEmptyMessage(MeetingReturned.CODE_NO_RESPONSE);
							}
						}
					} else {
						mRefresher.sendEmptyMessage(ret.operCode);
					}
				} else {
					mRefresher
							.sendEmptyMessage(MeetingReturned.CODE_NO_RESPONSE);
				}
				break;
			case REQ_ENTER_ROOM:
				roomPassowrd = (String) msg.obj;

				MeetingReturned ret2 = mMeetingApi.enterRoom(mRoomId,
						roomPassowrd);
				if (ret2 != null) {
					if (ret2.operCode == MeetingReturned.CODE_OK) {
						Meeting.current.roomId = mRoomId;
						Meeting.current.roomName = ret2.roomName;
						Meeting.current.baseTime = SystemClock
								.elapsedRealtime();
						Meeting.current.startTime = System.currentTimeMillis();
						Meeting.current.isMute = false;
						mRefresher.sendEmptyMessage(REFRESH_ENTER_MEETING_ROOM);
					} else {
						mRefresher.sendEmptyMessage(ret2.operCode);
					}
				} else {
					mRefresher
							.sendEmptyMessage(MeetingReturned.CODE_NO_RESPONSE);
				}
				break;
			}
		}
	}

	private class Refresher extends Handler {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			mWaitDialog.cancel();
			String hint = null;
			switch (msg.what) {
			case REFRESH_ENTER_MEETING_ROOM:
				Intent meeting = new Intent(context, MeetingActivity.class);
				context.startActivity(meeting);
				break;
			case REFRESH_SHOW_PASSWORD_DIALOG:
				showPasswordDialog();
				break;
			case MeetingReturned.CODE_ROOM_NOT_EXISTED:
				hint = "您输入的会议室号码不存在，请重试";
				break;
			case MeetingReturned.CODE_ROOM_PASSWORD_WRONG:
				hint = "您输入的会议室密码错误，请重试";
				break;
			case MeetingReturned.CODE_NO_RESPONSE:
				hint = "服务器无响应，请稍后再试";
				break;
			}

			if (hint != null) {
				Toast toast = Toast.makeText(context, hint, Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
			}
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		showWaitDialog();

		mRoomId = mFavs.get(position).get(Favorite.KEY_ROOM_ID);
		mRequester.sendEmptyMessage(REQ_KNOCK_ROOM);
	}

}
